package com.hbnu.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author kittychen
 * @since 2025-10-30 19:56
 */
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            // 1、创建ServerSocket对象
            serverSocket = new ServerSocket(8888);   // 监听8888端口
            System.out.println("等待连接...");

            // 2、获取连接
            Socket socket = serverSocket.accept();   // accept方法是阻塞式方法，等待客户端连接

            // 3、获取流资源(输入流)
            InputStream inputStream = socket.getInputStream();

            // 4、接收客户端数据
            // 获取客户端ip
            String ip = socket.getInetAddress().getHostAddress();
            byte[] buffer = new byte[1024];
            int len = inputStream.read(buffer);
            System.out.println("接收到了客户端" + ip + "发送的数据：" + new String(buffer, 0, len));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                // 5、释放资源
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
